package com.common.groovy.binding;

import com.common.groovy.GroovyModel;
import com.common.groovy.adapter.GroovyModelAdapter;
import groovy.lang.Binding;
import groovy.lang.MissingPropertyException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * @Description: 系统默认的参数绑定
 * @Date: 2025/6/30 14:02
 */
@Component
public class SystemDefaultBinding extends Binding implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Autowired
    @Lazy
    private GroovyModelAdapter groovyModelAdapter;

    @Override
    public Object getVariable(String name) {
        try {
            return super.getVariable(name);
        }catch (MissingPropertyException e){
            if(applicationContext.containsBean(name)){
                return applicationContext.getBean(name);
            }
            //可能是其他的model
            return new GroovyModel(name, groovyModelAdapter);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
